package com.googlecode.afdbaccess.config.injectconfig;

import javax.annotation.PreDestroy;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

import org.apache.log4j.Logger;

import com.googlecode.afdbaccess.cache.DbCache;
import com.googlecode.afdbaccess.cache.connectionpool.StandardDataSourcePool;

@ApplicationScoped
public class InjectableCacheReferenceHolder {
    private final static Logger log = Logger.getLogger(InjectableCacheReferenceHolder.class);
    
    private DbCache dbCache;
    
    protected InjectableCacheReferenceHolder() {
        // do nothing
    }

    @Inject
    protected InjectableCacheReferenceHolder(DataSourceLocator dataSourceLocator) {
        log.info("constructor");
        dbCache = new DbCache(new StandardDataSourcePool(dataSourceLocator.getDataSource()));
    }

    @PreDestroy
    protected void close() {
        if(dbCache != null) {
            log.info("Closing");
            dbCache.close();
            dbCache = null;
        } else {
            log.debug("dbCache is null, so nothing to close (this is OK if close has already been called earlier)");
        }
    }

    public DbCache getDbCache() {
        return dbCache;
    }
}
